<?php
namespace app\common\model\factory;

use think\Model;
use app\common\model\user\User;

class Factory extends Model
{
    protected $table = 'factory';
    protected $pk = 'factory_id';

    // 关联工厂员工
    public function users()
    {
        return $this->belongsToMany(
            User::class,
            'user_factory',
            'user_id',
            'factory_id'
        )->where('Role', 302); // 限定为工厂员工角色
    }

    
    // 获取工厂员工列表
    public function getStaffList($factoryId, $keyword = '', $page = 1, $pageSize = 10)
    {
        $query = $this->with(['users' => function ($q) use ($keyword) {
            $q->field('UserId, Iphone, Name, Sex');
            if ($keyword) {
                $q->where('Name', 'like', "%{$keyword}%");
            }
        }])->where('factory_id', $factoryId);

        return $query->findOrEmpty()->users()->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
            'query' => request()->param()
        ]);
    }

    // 添加员工到工厂
    public function addStaff($factoryId, $data)
    {
        $this->startTrans();
        try {
            // 创建用户
            $user = User::create([
                'Iphone' => $data['Iphone'],
                'Name' => $data['Name'],
                'Sex' => $data['sex'],
                'Role' => 302,
                'State' => User::STATEOK
            ]);

            // 关联用户到工厂
            $this->where('factory_id', $factoryId)
                ->relation('users')
                ->save($user);

            $this->commit();
            return $user;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }
}